<template>
  <div>
    <el-table :data="orders" style="width: 100%">
      <el-table-column prop="id" label="订单编号"></el-table-column>
      <el-table-column prop="created_at" label="订单日期"></el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <span class="status-label" :style="getStatusStyle(row.status)">
            {{ row.status }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="总价">
        <template #default="{ row }">
          {{ row.totalPrice.toFixed(2) }}元
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="mini"
                     @click="confirmCancelOrder(row)"
                     :disabled="row.status === 'COMPLETED' || row.status === 'CANCELLED'">
            退单
          </el-button>
          <el-button size="mini" @click="showOrderDetails(row.id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailsVisible" title="订单详情" width="70%">
      <el-table :data="selectedOrder.items" style="width: 100%">
        <el-table-column prop="drugName" label="药品名称"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column prop="price" label="单价"></el-table-column>
        <el-table-column label="总价">
          <template #default="{ row }">
            {{ formatCurrency(calculateTotal(row)) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="toggleDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getOrders, getOrderDetails, cancelOrder } from '@/api/order';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import api from "@/api/api";

export default {
  setup() {
    const orders = ref([]);
    const detailsVisible = ref(false);
    const selectedOrder = ref({});


    // 计算总价
    const calculateTotal = (row) => {
      return row.quantity * row.price;
    };

    // 获取订单列表
    const fetchOrders = async () => {
      try {
        const response = await getOrders();
        orders.value = response.map(order => ({
          ...order,
          created_at: dayjs(order.created_at).format('YYYY-MM-DD HH:mm:ss')
        }));
      } catch (error) {
        ElMessage.error("获取订单失败: " + error.message);
      }
    };


// 获取订单详情
    const showOrderDetails = async (orderId) => {
      try {
        const response = await getOrderDetails(orderId);
        if (response) {
          const itemsWithDrugNames = await Promise.all(response.items.map(async item => {
            try {
              const drugResponse = await api.get(`/api/drugs/${item.drugId}`);
              return { ...item, drugName: drugResponse.data.name };
            } catch (error) {
              console.error("获取药品详情失败:", error);
              return { ...item, drugName: "未知药品" };
            }
          }));
          selectedOrder.value = { ...response, items: itemsWithDrugNames };
          detailsVisible.value = true;
        } else {
          ElMessage.error('订单详情未找到');
        }
      } catch (error) {
        // 在这里处理错误，可以选择忽略或以其他方式处理
        console.error('获取订单详情失败:', error);
        ElMessage.error('获取订单详情失败');
      }
    };


// 确认取消订单
    const confirmCancelOrder = async (row) => {
      if (row.status === 'COMPLETED' || row.status === 'CANCELLED') {
        ElMessage.info('订单无法取消');
        return;
      }
      try {
        await ElMessageBox.confirm('确定要取消这个订单吗？', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await cancelOrder(row.id);
        row.status = 'CANCELLED';
        ElMessage.success('订单已取消');
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消订单失败: ' + error.message);
        } else {
          ElMessage.info('取消操作已撤销');
        }
      }
    };

    // 切换对话框可见性
    const toggleDialog = () => {
      detailsVisible.value = !detailsVisible.value;
    };

    const getStatusStyle = (status) => {
      switch (status) {
        case 'CANCELLED':
          return { color: '#ffffff', backgroundColor: '#e74c3c', borderRadius: '10px', padding: '3px 8px' };
        case 'PROCESSING':
          return { color: '#ffffff', backgroundColor: '#f39c12', borderRadius: '10px', padding: '3px 8px' };
        case 'COMPLETED':
          return { color: '#ffffff', backgroundColor: '#2ecc71', borderRadius: '10px', padding: '3px 8px' };
        default:
          return { color: '#ffffff', backgroundColor: '#3498db', borderRadius: '10px', padding: '3px 8px' };
      }
    };

    // 格式化货币
    const formatCurrency = (value) => {
      return `$${value.toFixed(2)}`;
    };

    onMounted(fetchOrders);

    return { orders, detailsVisible, selectedOrder, showOrderDetails, getStatusStyle, confirmCancelOrder, formatCurrency, calculateTotal, toggleDialog };
  },
};
</script>

<style>
.status-label {
  display: inline-block;
  text-align: center;
  min-width: 70px; /* Ensure the label is wide enough */
}
.dialog-footer {
  text-align:right;
}
</style>
